package top.huxy.boot.config;

import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Classname MybatisCache
 * @Description MybatisCache
 * @Date 2021/9/27 17:03
 * @Created by huxy
 */
public class MybatisCache implements Cache {
    /**
     * 读写锁
     */
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    /**
     * ID
     */
    private String id;

    /**
     * 集成redisTemplate
     */
    private static RedisTemplate<String, Object> redisTemplate;

    public MybatisCache() {
    }

    public MybatisCache(String id) {
        if (id == null) {
            throw new IllegalArgumentException("Cache instances require an ID");
        } else {
            this.id = id;
            redisTemplate.delete(id);
        }
    }


    @Override
    public String getId() {
        return this.id;
    }

    @Override
    public int getSize() {
        try {
            Long size = redisTemplate.opsForHash().size(this.id);
            return size.intValue();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public void putObject(final Object key, final Object value) {
        try {
            redisTemplate.opsForHash().put(this.id, key.toString(), value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object getObject(final Object key) {
        try {
            return redisTemplate.opsForHash().get(this.id, key.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Object removeObject(final Object key) {
        try {
            redisTemplate.opsForHash().delete(this.id, key.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void clear() {
        try {
            redisTemplate.delete(this.id);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return this.readWriteLock;
    }

    @Override
    public String toString() {
        return "MybatisRedisCache {" + this.id + "}";
    }

    /**
     * 设置redisTemplate
     *
     * @param redisTemplate
     */
    public static void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        MybatisCache.redisTemplate = redisTemplate;
    }
}
